<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Search, 
  Upload, 
  More, 
  Picture, 
  Close, 
  Plus, 
  Delete,
  VideoPlay
} from '@element-plus/icons-vue'
import { tagApi } from '@/api/tag'
import { ElMessage } from 'element-plus'
import { videoApi } from '@/api/video'
import VideoPlayer from '@/components/VideoPlayer.vue'

const router = useRouter()
const videos = ref([])
const loading = ref(false)
const searchText = ref('')
const tags = ref([])
const myTags = ref([])
const allTags = ref([])

// 添加 activeTag 的定义
const activeTag = ref(null)

// 在 script setup 中添加分页相关的变量
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 检查登录状态
const isLoggedIn = computed(() => {
  return !!localStorage.getItem('token')
})

// 获取用户信息
const userInfo = computed(() => {
  const userStr = localStorage.getItem('user')
  return userStr ? JSON.parse(userStr) : null
})

// 获取标签列表
const fetchTags = async () => {
  try {
    // 获取所有标签
    const tagRes = await tagApi.getTagList()
    if (tagRes.code === 1) {
      allTags.value = tagRes.data
    }

    // 如果用户已登录，获取用户喜欢的标签
    if (localStorage.getItem('token')) {
      const userTagRes = await tagApi.getUserLikeTags()
      if (userTagRes.code === 1) {
        myTags.value = userTagRes.data
      }
    }
  } catch (error) {
    ElMessage.error('获取标签列表失败')
  }
}

// 用户喜欢的标签
const userLikeTags = ref([])

// 获取用户喜欢的标签
const fetchUserLikeTags = async () => {
  try {
    const res = await tagApi.getUserLikeTags()
    if (res.code === 1) {
      userLikeTags.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取用户标签失败')
  }
}

// 添加喜欢的标签
const addUserLikeTag = async (tag) => {
  // 先检查是否登录
  if (!localStorage.getItem('token')) {
    router.push('/login')
    return
  }

  try {
    const res = await tagApi.addUserLikeTag(tag)
    if (res.code === 1) {
      ElMessage.success('添加成功')
      await fetchUserLikeTags()
    }
  } catch (error) {
    ElMessage.error('添加失败')
  }
}

// 移除喜欢的标签
const removeUserLikeTag = async (tag) => {
  // 先检查是否登录
  if (!localStorage.getItem('token')) {
    router.push('/login')
    return
  }

  try {
    const res = await tagApi.removeUserLikeTag(tag)
    if (res.code === 1) {
      ElMessage.success('移除成功')
      await fetchUserLikeTags()
    }
  } catch (error) {
    ElMessage.error('移除失败')
  }
}

// 判断标签是否被用户选择
const isTagLiked = (tagId) => {
  return userLikeTags.value.some(tag => tag.id === tagId)
}

onMounted(() => {
  // 获取视频列表数据
  fetchVideos()
  // 获取所有标签数据
  fetchTags()
  if (localStorage.getItem('token')) {
    fetchUserLikeTags()
  }
  window.addEventListener('scroll', loadMore)
})

onUnmounted(() => {
  window.removeEventListener('scroll', loadMore)
})

const showAllCategories = ref(false)

const toggleAllCategories = () => {
  showAllCategories.value = !showAllCategories.value
}

// 根据标签名获取对应的图标
const getTagIcon = (tagName) => {
  const iconMap = {
    '游戏': 'icon-game',
    '动漫': 'icon-anime',
    '音乐': 'icon-music',
    '电影': 'icon-movie',
    '生活': 'icon-life',
    '美食': 'icon-food',
    '旅游': 'icon-travel',
    '科技': 'icon-tech',
    '体育': 'icon-sports',
    '舞蹈': 'icon-dance'
  }
  return iconMap[tagName] || 'icon-tag'
}

// 添加新的响应式变量
const finished = ref(false)

// 修改获取视频列表的方法
const fetchVideos = async () => {
  if (loading.value || finished.value) return
  
  try {
    loading.value = true
    
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: 1,
      title: searchText.value || undefined,
      tagIds: activeTag.value ? [activeTag.value] : undefined
    }
    
    const res = await videoApi.getVideoList(params)
    
    if (res.code === 1) {
      const { records, total } = res.data
      
      // 修改视频数据映射，确保包含标签列表
      const mappedVideos = records.map(video => ({
        id: video.id,
        userId: video.userId,
        title: video.title,
        description: video.description,
        thumbnail_path: video.thumbnailPath,
        video_path: video.filePath,
        duration: video.duration || 0,
        views: video.views || 0,
        created_at: video.createdAt,
        updated_at: video.updatedAt,
        is_public: video.isPublic,
        status: video.status,
        likes_count: video.likesCount || 0,
        shares_count: video.sharesCount || 0,
        favorites_count: video.favoritesCount || 0,
        username: video.username,
        tagList: video.tagList || []
      }))
      
      videos.value = [...videos.value, ...mappedVideos]
      
      if (videos.value.length >= total) {
        finished.value = true
      } else {
        currentPage.value++
      }
    }
  } catch (error) {
    ElMessage.error('获取视频列表失败')
  } finally {
    loading.value = false
  }
}

// 添加滚动监听
const loadMore = () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  const clientHeight = document.documentElement.clientHeight
  const scrollHeight = document.documentElement.scrollHeight
  
  // 当滚动到距离底部100px时加载更多
  if (scrollHeight - scrollTop - clientHeight <= 100 && !loading.value && !finished.value) {
    fetchVideos()
  }
}

// 修改标签点击处理方法
const handleTagClick = async (tagId) => {
  // 如果在视频播放页面，先返回主页
  if (currentVideo.value) {
    currentVideo.value = null
  }
  
  // 设置选中的标签
  activeTag.value = tagId
  
  // 重置列表并重新加载
  videos.value = []
  currentPage.value = 1
  finished.value = false
  fetchVideos()
}

// 修改 watch 监听
watch([searchText, activeTag], () => {
  // 只有当不在视频播放页面时才重新加载列表
  if (!currentVideo.value) {
    videos.value = []
    currentPage.value = 1
    finished.value = false
    fetchVideos()
  }
})

// 格式化视频时长
const formatDuration = (seconds) => {
  if (!seconds) return '00:00'
  
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  
  const paddedMinutes = String(minutes).padStart(2, '0')
  const paddedSeconds = String(remainingSeconds).padStart(2, '0')
  
  return `${paddedMinutes}:${paddedSeconds}`
}

// 格式化播放量
const formatViews = (views) => {
  if (!views) return '0'
  
  if (views >= 100000000) {
    return (views / 100000000).toFixed(1) + '亿'
  } else if (views >= 10000) {
    return (views / 10000).toFixed(1) + '万'
  } else {
    return views.toString()
  }
}

// 在 script setup 中添加格式化时间的函数
const formatPublishTime = (timestamp) => {
  if (!timestamp) return ''
  
  const now = new Date()
  const publishTime = new Date(timestamp)
  const timeDiff = now - publishTime
  
  // 转换为相应的时间单位
  const minutes = Math.floor(timeDiff / (1000 * 60))
  const hours = Math.floor(timeDiff / (1000 * 60 * 60))
  const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24))
  
  // 如果小1小时
  if (hours < 1) {
    return minutes <= 0 ? '刚刚' : `${minutes}分钟前`
  }
  
  // 如果小于24小时
  if (days < 1) {
    return `${hours}小时前`
  }
  
  // 如果小于15天
  if (days < 15) {
    return `${days}天前`
  }
  
  // 超过15天显示具体日期
  const year = publishTime.getFullYear()
  const month = String(publishTime.getMonth() + 1).padStart(2, '0')
  const day = String(publishTime.getDate()).padStart(2, '0')
  
  // 如果是当年发布的，只显示月日
  if (year === now.getFullYear()) {
    return `${month}-${day}`
  }
  
  // 不是当年发布的，显示完整年月日
  return `${year}-${month}-${day}`
}

// 在 script setup 中添加览视频的定时器和状态
const previewTimeouts = ref({})  // 存储预览定时器
const previewStates = ref({})    // 存储预览状态

// 修改鼠标悬停处理方法
const handleVideoHover = (video) => {
  // 清除之前的定时器
  if (previewTimeouts.value[video.id]) {
    clearTimeout(previewTimeouts.value[video.id])
  }
  
  // 设置2秒后开始预览
  previewTimeouts.value[video.id] = setTimeout(() => {
    previewStates.value[video.id] = true
    // 获取视频元素并播放
    const videoElement = document.querySelector(`#preview-video-${video.id}`)
    if (videoElement) {
      videoElement.muted = true  // 设置静音
      videoElement.currentTime = 0  // 从头开始播放
      videoElement.play().catch(() => {
        // 如果自动播放失败，回退到显示封面图
        previewStates.value[video.id] = false
      })
    }
  }, 2000)  // 2秒后开始预览
}

// 添加鼠标离开处理方法
const handleVideoLeave = (video) => {
  // 清除定时器
  if (previewTimeouts.value[video.id]) {
    clearTimeout(previewTimeouts.value[video.id])
    delete previewTimeouts.value[video.id]
  }
  
  // 停止预览
  previewStates.value[video.id] = false
  
  // 重置视频
  const videoElement = document.querySelector(`#preview-video-${video.id}`)
  if (videoElement) {
    videoElement.pause()
    videoElement.currentTime = 0
  }
}

// 在 script setup 中添加
const currentVideo = ref(null)

// 修改播放视频的方法
const playVideo = async (video) => {
  try {
    await videoApi.addVideoCount(video.id)
    video.views++
  } catch (error) {
    ElMessage.error('播放量更新失败')
  }
  currentVideo.value = video
}

// 关闭播放器
const closePlayer = () => {
  currentVideo.value = null
}

// 在 script setup 中添加标签相关的方法
const addToMyTags = async (tag) => {
  try {
    // 检查登录状态
    if (!localStorage.getItem('token')) {
      router.push('/login')
      return
    }

    const res = await tagApi.addUserLikeTag(tag)
    if (res.code === 1) {
      ElMessage.success('添加成功')
      await fetchTags()
      await fetchUserLikeTags()
    } else {
      ElMessage.error(res.msg || '添加失败')
    }
  } catch (error) {
    ElMessage.error('添加失败，请重试')
  }
}

// 修改从我的分类中移除标签方法
const removeFromMyTags = async (tag) => {
  try {
    // 检查登录状态
    if (!localStorage.getItem('token')) {
      router.push('/login')
      return
    }

    const res = await tagApi.removeUserLikeTag(tag)
    if (res.code === 1) {
      ElMessage.success('移除成功')
      await fetchTags()
      await fetchUserLikeTags()
    } else {
      ElMessage.error(res.msg || '移除失败')
    }
  } catch (error) {
    ElMessage.error('移除失败，请重试')
  }
}
</script>

<template>
  <div class="home-container">
    <!-- 左侧分类导航 -->
    <div class="category-menu">
      <div class="section-title">我的分类</div>
      <div class="category-list">
        <div 
          class="category-item" 
          :class="{ active: !activeTag }"
          @click="handleTagClick(null)"
        >
          <i class="icon-all"></i>
          <span>全部</span>
        </div>
        <div 
          v-for="tag in myTags"
          :key="tag.id"
          class="category-item"
          :class="{ active: activeTag === tag.id }"
        >
          <div class="category-content" @click="handleTagClick(tag.id)">
            <i :class="getTagIcon(tag.name)"></i>
            <span>{{ tag.name }}</span>
          </div>
          <el-icon 
            class="remove-icon"
            @click.stop="removeFromMyTags(tag)"
          >
            <Delete />
          </el-icon>
        </div>
      </div>

      <div class="section-title">全部分类</div>
      <div class="category-list">
        <div 
          v-for="tag in allTags"
          :key="tag.id"
          class="category-item"
          :class="{ active: activeTag === tag.id }"
        >
          <div class="category-content" @click="handleTagClick(tag.id)">
            <i :class="getTagIcon(tag.name)"></i>
            <span>{{ tag.name }}</span>
          </div>
          <!-- 如果不在我的标签中，显示添加按钮 -->
          <el-icon 
            v-if="!myTags.some(t => t.id === tag.id)"
            class="add-icon"
            @click.stop="addToMyTags(tag)"
          >
            <Plus />
          </el-icon>
        </div>
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="content-wrapper">
      <!-- 视频列表 -->
      <div v-if="!currentVideo" class="video-list">
        <div 
          v-for="video in videos" 
          :key="video.id" 
          class="video-item"
          @click="playVideo(video)"
          @mouseenter="handleVideoHover(video)"
          @mouseleave="handleVideoLeave(video)"
        >
          <div class="video-cover">
            <!-- 缩略图 -->
            <el-image 
              v-show="!previewStates[video.id]"
              :src="video.thumbnail_path" 
              fit="cover"
              loading="lazy"
            />
            <!-- 预览视频 -->
            <video
              v-show="previewStates[video.id]"
              :id="`preview-video-${video.id}`"
              :src="video.video_path"
              class="preview-video"
              muted
              loop
              playsinline
              preload="metadata"
            ></video>
            <div class="video-duration">{{ formatDuration(video.duration) }}</div>
          </div>
          <div class="video-info">
            <div class="video-title">{{ video.title }}</div>
            <div class="video-meta">
              <div class="play-info">
                <span class="play-count">{{ formatViews(video.views) }}播放</span>
                <span class="dot">·</span>
                <span class="publish-time">{{ formatPublishTime(video.created_at) }}</span>
              </div>
              <div class="author-info">
                <span class="up-name">{{ video.username }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 视频播放器 -->
      <div v-else class="video-player-container">
        <VideoPlayer
          :video="currentVideo"
          :related-videos="videos"
          :format-views="formatViews"
          :format-duration="formatDuration"
          :format-publish-time="formatPublishTime"
          @close="closePlayer"
          @change="playVideo"
        />
      </div>
    </div>
  </div>
</template>

<style>
@import '../css/home.css';
</style>

